<template>
	<view class="ring-container" @touchmove.stop="">
		<!-- 电量 日历 元气 -->
		<view v-if="!notTest" class="header">
			<view class="left">
				<BatteryLevel @click="toMsg" />
				<image class="tapd" src="../../static/ring/chart/tapd.png" mode="" @click="toTask"></image>
			</view>
			<view class="calendar" @click="openCalendar">
				<uni-icons type="left" size="16" color="black"></uni-icons>
				<text class="day">{{ headDay }}</text>
				<uni-icons type="right" size="16" :style="{ color: isToday(currentDate) ? '#999999' : '#000000' }"></uni-icons>
			</view>
			<view class="right">
				<!-- <view @click="in2Search" >搜索</view> -->
				<image src="/static/yuanqi.png" />
<!--				<image src="/static/yuanqi1.png" />-->
			</view>
		</view>

		<!-- 滚动模块 @click.stop="handleClearCardChoose" -->
		<scroll-view v-if="!notTest" scroll-y class="scroll_view">
			<BlueLinkStatus />
			<LinkHeader />
      <view v-if="!notTest" class="main_box" style="margin-bottom: 32rpx">
        <AiPointReport :key="(syncKeys + 1) * 2" :date="currentDate" />
      </view>
			<DailyTask :hasSleep="showTask" @report="
          showSleepReport = true;
          showTask = false;
        " />
			<NewComerChallenge @getGift="getGift" />
			<view v-if="!notTest" class="main_box">
				<ChartMain :key="(syncKeys + 1) * 3" :date="currentDate" @onDetection="onDetection" />
			</view>
		</scroll-view>

		<uni-calendar v-if="!notTest" ref="calendar" :insert="false" :lunar="false" start-date="2024-01-01"
			:end-date="today" :selected="selected" @monthSwitch="calendarMonthChange" @change="calendarChange" />

		<Detection v-if="!notTest" v-model="showDetection" :type="detectionType" />

		<!-- <SleepReport v-model="showSleepReport" :data="sleepData" /> -->

		<BatteryAlert v-if="!notTest" v-model="showBatteryAlert" :battery="batteryLevel" />

		<!-- <VigorGetterAlert v-model="showVigor" /> -->
		<!-- <GiftGetterAlert /> -->
		<!-- <DailyHealthRewardsAlert v-model="showSleepReport" /> -->

		<view v-if="notTest" class="not_internal_test">
			<view v-if="!showKF" class="test_main">
				<h2>内测资格提示</h2>
				<view class="tip">您当前未获得内测资格，如需参与请联系官方客服或关注后续招募活动。</view>
				<view v-if="isLogin" class="learn_more" @click="showKF = true">了解更多</view>
				<view v-else class="learn_more" @click="toLogin">立即登录</view>
			</view>

			<view v-else class="text_fk">
				<h2>官方客服</h2>
				<view class="img_box">
					<image src="@/static/ring/qsxd.png" mode="widthFix" />
					<view class="tip">即刻添加官方客服，了解更多</view>
				</view>
				<view class="learn_close" @click="showKF = false">关闭</view>
			</view>
		</view>
		<view v-if="default_dialog" class="not_internal_test"
			style="z-index: 9999; background-color: rgb(192, 219, 253)"></view>

		<FirstConnect ref='firstConnect' />
		<FirstSynchronous ref='firstSynchronous' />
		<GuideIndex ref='guideIndex' />

	</view>
</template>
<script>
	import dayjs from "dayjs";
	import BatteryLevel from "./components/BatteryLevel.vue";
	import LinkHeader from "./components/LinkHeader.vue";
	import AiPointReport from "./components/AiPointReport.vue";
	import ChartMain from "./components/ChartMain.vue";
	import BlueLinkStatus from "./components/BlueLinkStatus.vue";
	import Detection from "./components/Detection.vue";
	import SleepReport from "./components/drawer/SleepReport.vue";
	import BatteryAlert from "./components/drawer/BatteryAlert.vue";
	import VigorGetterAlert from "./components/drawer/VigorGetterAlert.vue";
	import GiftGetterAlert from "./components/drawer/GiftGetterAlert.vue";
	import DailyHealthRewardsAlert from "./components/drawer/DailyHealthRewardsAlert.vue";
	import NewComerChallenge from "./components/NewComerChallenge.vue";
	import DailyTask from "./components/DailyTask.vue";
	import FirstConnect from "./components/FirstConnect.vue";
	import FirstSynchronous from "./components/FirstSynchronous.vue";
	import GuideIndex from "./components/GuideIndex.vue";

	import {
		healthCal,
		needReceiveAward
	} from "@/api/ring/report.js";
	import {
		queryMySleepInfoByDay
	} from "@/api/ring/chart.js";
	import {
		getUserInfo
	} from "@/api/ring/user.js";
	import {
		getUserRing
	} from "@/utility/business.js";
	import store from "@/store/index";
	import {
		mapGetters
	} from "vuex";
	import {
		getLatestUpdateTime
	} from "@/api/ring/report.js";

	const typeMap = {
		1: "normal",
		2: "error",
		3: "warning",
		4: "success",
	};

	export default {
		components: {
			GuideIndex,
			FirstSynchronous,
			FirstConnect,
			BatteryLevel,
			LinkHeader,
			ChartMain,
			AiPointReport,
			BlueLinkStatus,
			Detection,
			SleepReport,
			BatteryAlert,
			VigorGetterAlert,
			GiftGetterAlert,
			DailyHealthRewardsAlert,
			NewComerChallenge,
			DailyTask,
		},
		data() {
			return {
				currentDate: dayjs().format("YYYY-MM-DD"),
				selected: [],

				syncKeys: 0,

				showDetection: false,
				detectionType: "",
				showSleepReport: false,
				sleepData: null,
				showBatteryAlert: false,
				showVigor: false,
				showTask: true,
				notTest: true,
				showKF: false,
				default_dialog: true,
			};
		},

		computed: {
			...mapGetters(["statusBarHeight", "hideRing"]),

			isLogin() {
				return store.state.userToken;
			},

			headDay() {
				return this.currentDate === dayjs().format("YYYY-MM-DD") ?
					"今日" :
					this.currentDate;
			},

			today() {
				return dayjs().format("YYYY-MM-DD");
			},

			syncLoading() {
				return this.$store.state.ringDataManage.syncLoading;
			},

			batteryLevel() {
				return Number(store.state.ringDataManage.battery.batteryLevel);
			},

			batteryCharging() {
				return store.state.ringDataManage.battery.batteryCharging;
			},

			canShowBatteryAlert() {
				return [this.syncLoading, this.batteryLevel, this.batteryCharging];
			},
		},

		watch: {
			syncLoading(nv, ov) {
				// nv = false 且 ov = true是同步完成
				if (!nv && ov) {
					this.syncKeys++;
					this.$nextTick(() => {
						this.getRingUserInfo();
						this.checkNeedReceivePoint();
					});
				}
			},

			syncKeys() {
				this.getCalendarSleepDayDot(dayjs(this.currentDate).format("YYYY-MM"));
			},

			canShowBatteryAlert: {
				handler(nv) {
					const [loading, battery, isCharging] = nv;
					console.log(
						"🔋🔋🔋🔋🔋🔋🔋🔋🔋电量变化🔋🔋🔋🔋🔋🔋🔋🔋",
						battery,
						battery <= 30
					);
					if (loading) return;
					console.log("🔋🔋🔋🔋🔋🔋🔋🔋🔋 同步完成 电量变化🔋🔋🔋🔋🔋🔋🔋🔋");

					this.showBatteryAlert = battery <= 30 && !isCharging;
				},
				deep: true,
			},

			hideRing(nv) {
				this.notTest = nv;
				this.showKF = false;
			},
		},

		async mounted() {
			const result = await getUserRing();
			if (result === 800 || !result) {
				this.notTest = true;
				this.default_dialog = false;
				store.commit("setHideRingPage", true);
				return;
			}
			this.notTest = false;
			this.default_dialog = false;
			store.commit("setHideRingPage", false);

			this.getLastUpdateTime();
			this.getCalendarSleepDayDot(dayjs(this.currentDate).format("YYYY-MM"));
			this.getRingUserInfo();
			this.checkNeedReceivePoint();
		},

		methods: {
			toLogin() {
				uni.navigateTo({
					url: "/pages/user/login",
				});
			},
			toMsg() {
				uni.navigateTo({
					url: "/pages/ring/ringMsg",
				});
			},
			toTask() {
				uni.navigateTo({
					url: "/pages/ring/task",
				});
			},
			getLastUpdateTime() {
				getLatestUpdateTime().then((res) => {
					store.commit("ringDataManage/SET_LAST_UPDATE_TIME", res.data || {});
				});
			},
			getRingUserInfo() {
				getUserInfo()
					.then((res) => {
						this.$store.dispatch("setRingUser", res.data);
					})
					.catch((error) => {
						console.log("getUserInfo error", error);
					});
			},

			openCalendar() {
				this.$refs.calendar.open();
			},

			closeCalender() {
				this.$refs.calendar.close();
			},

			calendarChange(date) {
				this.closeCalender();
				this.currentDate = date.fulldate;
			},

			calendarMonthChange(date) {
				const month = ("0" + date.month).slice(-2);
				const ym = `${date.year}-${month}`;
				this.getCalendarSleepDayDot(ym);
			},

			getCalendarSleepDayDot(date) {
				if (!store.state.userToken) return;
				healthCal(date)
					.then((res) => {
						console.log("healthCal", res);
						this.selected = res.data
							.filter((item) => !!item.colorLevel && !!item.dateFormat)
							.filter((item) => {
								return dayjs(item.dateFormat).isBefore(dayjs());
							})
							.filter((item) => {
								return item.totalScore !== 0;
							})
							.map((item) => {
								return {
									date: item.dateFormat,
									type: typeMap[item.colorLevel],
								};
							});
					})
					.catch((err) => {
						console.log("healthCal", err);
					});
			},

			handleClearCardChoose() {},

			in2Search() {
				uni.navigateTo({
					url: "/pages/ring/search",
				});
			},

			onDetection(type) {
				this.showDetection = true;
				this.detectionType = type;
			},

			checkNeedReceivePoint() {
				queryMySleepInfoByDay({
					dateStr: dayjs().format("YYYY-MM-DD"),
					offsetMinutes: new Date().getTimezoneOffset(),
				}).then((res) => {
					this.sleepData = res.data;
					needReceiveAward({
							dateStr: dayjs().format("YYYY-MM-DD"),
						})
						.then((res) => {
							this.showSleepReport = res.data && res.success;
						})
						.catch((error) => {
							console.log("needReceiveAward error", error);
						});
				});
			},

			getGift(gift) {
				this.showVigor = true;
			},
			isToday(dateString) {
			      const today = new Date();
			      const inputDate = new Date(dateString);
			      
			      // 比较年月日是否相同
			      return (
			        inputDate.getFullYear() === today.getFullYear() &&
			        inputDate.getMonth() === today.getMonth() &&
			        inputDate.getDate() === today.getDate()
			      );
			    }
		},
	};
</script>
<style lang="scss" scoped>
	.ring-container {
		padding-top: var(--status-bar-height);
		overflow: hidden;
		//background-color: rgb(192, 219, 253);
		width: 100vw;
		height: 100vh;

		.not_internal_test {
			position: fixed;
			top: 0;
			left: 0;
			width: 100vw;
			height: 100vh;
			background-color: rgba(0, 0, 0, 0.5);
			z-index: 8888;

			display: flex;
			align-items: center;
			justify-content: center;

			.test_main,
			.text_fk {
				width: 620rpx;
				height: 416rpx;
				border-radius: 20rpx;
				background: linear-gradient(180deg, #dde6ff 0%, #ffffff 51.46%);
				padding: 60rpx 40rpx;
				display: flex;
				justify-content: space-between;
				flex-direction: column;
				align-items: center;

				.tip {
					font-size: 28rpx;
					font-weight: 400;
					line-height: 40rpx;
				}

				.learn_more,
				.learn_close {
					width: 100%;
					height: 80rpx;
					line-height: 80rpx;
					text-align: center;
					font-weight: bold;
					font-size: 32rpx;
					background: #2359f8;
					color: white;
					border-radius: 20rpx;
				}
			}

			.text_fk {
				height: 816rpx;

				.img_box {
					width: 100%;
					display: flex;
					flex-direction: column;
					align-items: center;
					justify-content: center;
				}

				image {
					width: 80%;
					border-radius: 20rpx;
				}
			}
		}

		.circle {
			transform: scale(0.5);
		}

		.header {
			width: 100vw;
			padding: 16rpx 32rpx;
			min-height: 56rpx;

			display: flex;
			justify-content: space-between;
			align-items: center;
			font-weight: 400;
			font-size: 36rpx;
			// background-color: rgb(210, 232, 247);
			color: black;

			&>view {
				flex: 1;
				text-align: center;
			}

			.left {
				display: flex;
				align-items: center;

				.tapd {
					height: 48rpx;
					width: 48rpx;
					margin-left: 30rpx;
				}
			}

			.calendar {
				display: flex;
				align-items: center;
				justify-content: center;

				text {
					font-size: 30rpx;
					font-weight: 600;
					line-height: 42rpx;
					text-align: center;

					color: black;
					text-align: center;
				}
			}

			.right {
				image {
					width: 48rpx;
					height: 48rpx;
					float: right;
				}
			}
		}

		.scroll_view {
			width: 100vw;
			// height: calc(100vh - var(--status-bar-height) - 56rpx);
			height: calc(100% - 80rpx);
		}

		.main_box {
			margin-top: 20px;
			padding: 0 32rpx 0 32rpx;
			width: 100%;
			// height: 110rpx;
		}
	}
</style>